package com.siwei.mes.sync.erp.service;

import com.alibaba.fastjson.JSON;
import com.siwei.mes.config.CompanyConfigInterceptor;
import com.siwei.mes.entity.sync.tc.SupplyTask;
import com.siwei.mes.entity.sync.tc.Waybill;
import com.siwei.mes.enums.MaterialsEnum;
import com.siwei.mes.enums.SyncEnum;
import com.siwei.mes.enums.WaybillStateEnum;
import com.siwei.mes.mapper.syncTc.SupplyTaskMapper;
import com.siwei.mes.mapper.syncTc.WaybillMapper;
import com.siwei.mes.service.materials.MaterialsService;
import com.siwei.mes.sync.config.SyncProcessorService;
import com.siwei.mes.sync.erp.entity.SyncErpWaybill;
import com.siwei.mes.sync.erp.enums.ErpOrgState;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;

/**
 * 同步ERP运单
 *
 * @Description: 同步ERP运单
 * @Version: 1.0
 * @author: mlchen
 * @date: 2025/3/19 22:05
 */
@Service
public class SyncErpWaybillService {
    private static final Logger log = LoggerFactory.getLogger("erp");
    @Resource
    private SyncProcessorService syncProcessorService;
    @Resource
    private MaterialsService materialsService;
    @Resource
    private WaybillMapper waybillMapper;
    @Resource
    private SupplyTaskMapper supplyTaskMapper;

    /**
     * 同步或新增erp运单
     *
     * @param syncInfo
     */
    public void saveOrUpdate(SyncErpWaybill syncInfo) {
        log.info("正在执行ERP新增或修改运单，入参：{}", JSON.toJSONString(syncInfo));
        String category = syncInfo.getCategory();
        log.info("ERP运单传入过来的类型：【{}】", category);

        String yclName = syncInfo.getYclName();
        String pzgg = syncInfo.getPzgg();
        MaterialsEnum materialsEnum = null;


        /**这里根据物料名称+物料规格 查询ERP传过来的物料类型是什么*/
        Integer materialsType = materialsService.getMaterialsType(yclName, pzgg);
        log.info("根据物料名称：【{}】,物料规格：【{}】查询出对应的物料类型：【{}】", yclName, pzgg, materialsType);
        if (materialsType == null) {
            materialsEnum = MaterialsEnum.selectByErpType(category);
        } else {
            materialsEnum = MaterialsEnum.selectByCode(materialsType);
        }

        if ("矿粉".equals(yclName)) {
            materialsEnum = MaterialsEnum.SLAG;
        }


        if (materialsEnum == null) {
            log.info("ERP新增或修改运单，原材料未配置此类型对照品控的类型，直接不做数据处理，对应类型：【{}】", category);
            return;
        }

        if (materialsEnum.getCode().equals(MaterialsEnum.CONCRETE.getCode())) {
            log.info("ERP新增或修改运单，原材料类型查询出混凝土，不做处理！");
            return;
        }

        Waybill waybill = SyncErpWaybill.payloadInfo(syncInfo);
        waybill.setProjectCategory(materialsEnum.getCode());
        if (syncInfo.getOrgState().equals(ErpOrgState.WXH)) {
            waybill.setState(WaybillStateEnum.WAIT_WEIGH.getCode());
        } else if (syncInfo.getOrgState().equals(ErpOrgState.YXH)) {
            waybill.setState(WaybillStateEnum.DONE.getCode());
        }

        boolean isUpdateWaybill = false;
        /**这里判断运单id是否存在 赋值对应的状态  第一次推送为新增数据  状态为待过磅  第二次推送过来为修改数据  状态为已完成*/
        Waybill selectedByWid = waybillMapper.selectByWid(syncInfo.getWLID());
        if (selectedByWid != null) {
            waybill.setId(selectedByWid.getId());
            waybill.setSupplyTaskId(selectedByWid.getSupplyTaskId());
            waybill.setGenQuickQuantity(selectedByWid.getGenQuickQuantity());
            waybill.setGenBatchQuantity(selectedByWid.getGenBatchQuantity());
            isUpdateWaybill = true;
        } else {
            waybill.setGenQuickQuantity(BigDecimal.ZERO);
            waybill.setGenBatchQuantity(BigDecimal.ZERO);
        }
        /**操作供货任务相关 没有就说明需要新增一条ERP的供货任务*/
        SupplyTask supplyTask = this.createSupplyTaskInfo(waybill, isUpdateWaybill);
        /**如果供货任务id为空*/
        if (waybill.getSupplyTaskId() == null) {
            waybill.setSupplyTaskId(supplyTask.getSupplyTaskId());
            waybill.setSupplyCompanyCompany(supplyTask.getSupplyCompanyCompany());
        }
        log.info("ERP新增或修改运单映射成品控的运单信息：【{}】", JSON.toJSONString(waybill));
        if (waybill.getId() == null) {
            waybillMapper.insertSelective(waybill);
        } else {
            waybillMapper.updateByPrimaryKeySelective(waybill);
        }
        /**判断是否有物料 如果没有则新增*/
        materialsService.checkIsExist(waybill.getProjectCategory(), waybill.getProjectName(), waybill.getProjectSpecs());
        /**这里丢到对应队列中去处理*/
        syncProcessorService.submitRequest(waybill);
    }

    /**
     * 创建运单对应的供货任务
     * 物料类型+物料名称+物料规则+供货商  要按天数来（任务派发时间） task_start_time
     *
     * @param waybill         运单信息
     * @param isUpdateWaybill 是否是修改运单
     * @return
     */
    private SupplyTask createSupplyTaskInfo(Waybill waybill, boolean isUpdateWaybill) {
        log.info("正在模拟创建运单对应的供货任务信息，运单信息：【{}】", JSON.toJSONString(waybill));
        /**查询对应的供货任务  物料类型+物料名称+物料规则+供货商  要按天数来（任务派发时间） task_start_time */
        SupplyTask supplyTask = supplyTaskMapper.selectByErpSupplyTaskToday(waybill.getProjectName(), waybill.getProjectSpecs(), waybill.getProjectCategory(), waybill.getSupplyCompanyCompany(), waybill.getFactory());
        log.info("查询运单对应的供货任务信息，任务派发时间为当天的，物料名称：【{}】,物料规格：【{}】,物料类型：【{}】,供货商：【{}】,生产厂家：【{}】", waybill.getProjectName(), waybill.getProjectSpecs(), waybill.getProjectCategory(), waybill.getSupplyCompanyCompany(), waybill.getFactory());
        if (supplyTask == null) {
            supplyTask = new SupplyTask();
            long maxSupplyTaskId = supplyTaskMapper.getMaxSupplyTaskId();

            supplyTask.setSupplyTaskId(maxSupplyTaskId + 1);
            supplyTask.setSupplyTaskCode("RW" + supplyTask.getSupplyTaskId());
            supplyTask.setProjectName(waybill.getProjectName());
            supplyTask.setProjectSpecs(waybill.getProjectSpecs());
            supplyTask.setProjectCategory(waybill.getProjectCategory());
            supplyTask.setFactory(waybill.getFactory());
            supplyTask.setSupplyPlanQuantity(null);
            supplyTask.setSupplySignQuantity(waybill.getSignQuantity());
            supplyTask.setTransportQuantity(BigDecimal.ZERO);

            supplyTask.setSupplyCompanyCompany(waybill.getSupplyCompanyCompany());
            supplyTask.setLogisticsCompanyCompany(null);
            supplyTask.setMixingPlantCompany(CompanyConfigInterceptor.getCompanyConfig(1).getCompanyName());
            supplyTask.setSupplyPlanTime(new Date());
            supplyTask.setTaskStartTime(new Date());
            supplyTask.setSyncType(SyncEnum.MOCK.getCode());
            supplyTask.setState(4);
            supplyTaskMapper.insertSelective(supplyTask);
        } else {
            if (isUpdateWaybill) {
                return supplyTask;
            }
            supplyTask.setSupplyPlanQuantity(null);
            supplyTask.setSupplySignQuantity(null);
            supplyTaskMapper.updateByPrimaryKeySelective(supplyTask);
        }
        return supplyTask;
    }
}
